package com.rongcheng.frc.newstyledemo.engine;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.rongcheng.frc.androidlib.activity.BaseActivity;
import com.rongcheng.frc.androidlib.net.DefaultThreadPool;
import com.rongcheng.frc.androidlib.net.HttpRequest;
import com.rongcheng.frc.androidlib.net.RequestCallback;
import com.rongcheng.frc.androidlib.net.RequestParameter;
import com.rongcheng.frc.androidlib.net.Response;
import com.rongcheng.frc.androidlib.net.URLData;
import com.rongcheng.frc.androidlib.net.UrlConfigManager;
import com.rongcheng.frc.androidlib.net.mock.MockConfigManager;
import com.rongcheng.frc.androidlib.net.mock.MockSettingData;
import com.rongcheng.frc.androidlib.net.mock.YXResponse;
import com.rongcheng.frc.newstyledemo.mockdata.MockService;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import static com.rongcheng.frc.androidlib.net.UrlConfigManager.findURL;

public class RemoteService {
    private static RemoteService service = null;
    private Response successResponse;
    private Response failResponse;


    private RemoteService() {

    }

    public static synchronized RemoteService getInstance() {
        if (RemoteService.service == null) {
            RemoteService.service = new RemoteService();
        }
        return RemoteService.service;
    }

    public void invoke(final BaseActivity activity,
                       final String apiKey,
                       final List<RequestParameter> params,
                       final RequestCallback callBack) {
        final URLData urlData = findURL(activity, apiKey);
        /**先判断整个app的网络框架是否为模拟状况**/
        Log.e("frc", "isLinkedService: :" + UrlConfigManager.isLinkedService);
        if (!UrlConfigManager.isLinkedService) {
            Log.e("frc", "isUseMockData: :" + urlData.isUseMockData());
            if (urlData.isUseMockData()) {//判断当前接口是否为模拟
                final MockSettingData mockSettingData = MockConfigManager.findMockConfig(activity, apiKey);

                String ClassName = urlData.getMockClass();
                if (ClassName != null) {
                    try {


                        switch (UrlConfigManager.ConnctedTime) {
                            case "1":
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case "2":
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case "3":
                                try {
                                    Thread.sleep(3000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case "4":
                                try {
                                    Thread.sleep(4000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                break;
                            default:
                                break;
                        }


                        String strResponse = getRandomResponse(activity, mockSettingData);
                        final YXResponse responseInJson = JSON.parseObject(strResponse,
                                YXResponse.class);
                        switch (responseInJson.getCode()) {
                            case "0":
                                callBack.onSuccess(responseInJson.getData(), true);
                                break;
                            case "1":
                            case "2":
                                callBack.onFail(responseInJson.getDesc(), true);
                                break;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            } else {
                Log.e("frc", "用真实网络");
            }
        } else {
            Log.e("frc", "用真实网络");

            HttpRequest request = activity.getRequestManager().createRequest(
                    urlData, params, callBack);
            DefaultThreadPool.getInstance().execute(request);
        }


    }

    /**
     * 根据设置的概率值获取返回数据
     *
     * @param mockSettingData
     */
    private String getRandomResponse(BaseActivity activity, MockSettingData mockSettingData) {
        Resources res = activity.getResources();
        AssetManager assetManager = activity.getAssets();
        Random random = new Random();
        String responseString = "";
        int tryTimes = mockSettingData.getErrorScale() + mockSettingData.getSuccessScale() + mockSettingData.getNetErrorScale();
        int randomCount = random.nextInt(tryTimes);

        if (randomCount < mockSettingData.getErrorScale() && randomCount >= 0) {
            responseString = getFailResponse(assetManager);

        } else if (randomCount < mockSettingData.getErrorScale() + mockSettingData.getSuccessScale() && randomCount >= mockSettingData.getErrorScale()) {
            responseString = getSuccessResponse(assetManager, mockSettingData);

        } else {

            responseString = getNetErrorResponse(assetManager);
        }

        return responseString;

    }

    private String getSuccessResponse(AssetManager assetManager, MockSettingData mockSettingData) {
        return getAssetsResourceToStr(mockSettingData.getMockFile(), assetManager);
    }

    private String getFailResponse(AssetManager assetManager) {
        return getAssetsResourceToStr("error_data_response", assetManager);
    }

    private String getNetErrorResponse(AssetManager assetManager) {
        return getAssetsResourceToStr("net_error_response", assetManager);
    }

    private String getAssetsResourceToStr(String fileName, AssetManager assetManager) {
        String responseString = "";
        try {
            InputStream inputStream = assetManager.open(fileName);
            int length = inputStream.available();
            byte[] buffer = new byte[length];
            inputStream.read(buffer);
            responseString = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.e("frc", responseString);
        return responseString;
    }
}